package com.sansi.bleFloodlight.utils;

import android.text.TextUtils;

import com.my.httpapi.api.baseUtils.LogUtils;
import com.my.httpapi.api.baseUtils.Toast;
import com.tencent.mmkv.MMKV;

import java.io.UnsupportedEncodingException;

public class ActivityUtils {
    private static final int TIME_EXIT = 2000;
    private static long mBackPressed;

    public static boolean isExit() {
        if (mBackPressed + TIME_EXIT > System.currentTimeMillis()) {
            mBackPressed = 0;
            return true;
        }
        Toast.show("再点击一次返回退出程序");
        mBackPressed = System.currentTimeMillis();
        return false;
    }

    public static byte[] getLocalNetKey() {
        //从本地获取netkey
        String localNetKey = MMKV.defaultMMKV().decodeString(MMKVUtils.NETKEY);
        if (!TextUtils.isEmpty(localNetKey)) {
            LogUtils.e("netkey:" + localNetKey);
            try {
                return localNetKey.getBytes("utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //本地沒有生成一个netkey-随机字符串+时间戳的组合
        String str = "";
        for (int i = 0; i < 3; i++) {
            str = str + (char) (Math.random() * 26 + 'a');
        }
        str = str + System.currentTimeMillis();
        //保持到本地
        MMKV.defaultMMKV().encode(MMKVUtils.NETKEY, str);
        LogUtils.e("netkey:" + str);
        try {
            return str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    public static byte[] getByte() {
        //获取单播地址
        String address = MMKV.defaultMMKV().decodeString(MMKVUtils.ADDRESS);
        if (TextUtils.isEmpty(address)) {
            address = "000A";
        } else {
            //本地的单播地址递增
            address = StringUtils.hexIncreaseN(address, 3);
        }
        //保存新的单播地址供下次使用
        MMKV.defaultMMKV().encode(MMKVUtils.ADDRESS, address);
        return toBytes(address);
    }

    /**
     * 将16进制字符串转换为byte[]
     *
     * @param str
     * @return
     */
    public static byte[] toBytes(String str) {
        if (str == null || str.trim().equals("")) {
            return new byte[0];
        }

        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length() / 2; i++) {
            String subStr = str.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(subStr, 16);
        }

        return bytes;
    }
}
